package com.meefo.meeting.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * –@Aspect: 把当前类标识为一个切面供容器读取
 * –@Pointcut: 定义一个切面
 * –@Before: 前置通知, 在方法执行之前执行
 * –@After: 后置通知, 在方法执行之后执行
 * –@AfterRunning: 返回通知, 在方法返回结果之后执行
 * –@AfterThrowing: 异常通知, 在方法抛出异常之后
 * –@Around: 环绕通知, 围绕着方法执行
 */
@Aspect
@Component
public class ApiAspect {

    @Autowired
    WriteExceptionToFileLog writeExceptionToFileLog;

    @Pointcut("execution(* com.meefo.meeting.web..*(..))")
    public void pointcut() {
    }

    //异常通知
    @AfterThrowing(value = "pointcut()", throwing = "ex")
    public void afterReturningMethod(JoinPoint joinPoint, Exception ex) {
        //错误日志
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String uri = request.getRequestURI();
        List<Object> ags = Arrays.asList(joinPoint.getArgs());
        String names = joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName();
        // 获取切入点所在的方法
        writeExceptionToFileLog.logException(names, ags.toString(), ex);
    }

}
